/* eslint-disable jsx-a11y/label-has-associated-control */
import React, { useEffect, useState } from "react";
import to from "await-to-js";
import MyAlert from "../../components/Alert";
import MyReset from "../../components/Reset";
import API from "../../api/LoginApi";
import { log } from "../../utils/logger";
import { useNavigate } from "react-router-dom";
import { getStore, setStore } from "../../utils/store";

function Login() {
  const [username, setUsername] = useState("admin");
  const [password, setPassword] = useState("123456");
  const [domain, setDomain] = useState("127.0.0.1");
  const [checkError, setCheckError] = useState("");
  const [isVisible, setIsVisible] = useState(false);
  const [isLoginIng, setIsLoginIng] = useState(false);

  useEffect(() => {
    let token = getStore("token");
    if (token) {
      navigate("/home");
    }
  }, []);

  let navigate = useNavigate();

  const handleLogin = async () => {

    log("######################handleLogin######################");
    setIsLoginIng(true);

    if (!username || !password) {
      setCheckError("请输入用户名和密码");
      setIsVisible(true);
      setTimeout(() => {
        setIsVisible(false);
      }, 3000);
      setIsLoginIng(false);
      return;
    }
    if (domain) {
      const serverIP = `http://${domain}`;
      window.Main.setStore("baseUrl", serverIP);
    } else {
      window.Main.setStore("baseUrl", "http://localhost");
    }

    const [e, _] = await to(API.healthyCheck());
    if (e) {
      setIsVisible(true);
      setCheckError("服务不在线，请检查");
      setTimeout(() => {
        setIsVisible(false);
      }, 3000);
      setIsLoginIng(false);
      return;
    }

    const [err, res] = await to(API.login(username, password));
    if (err) {
      console.log(`登录失败：${res}`);
      setIsVisible(true);
      setCheckError("登录失败，请检查用户账号与密码是否正确");
      setTimeout(() => {
        setIsVisible(false);
      }, 3000);
      setIsLoginIng(false);
      return;
    } else {
      log("登录成功");
      setStore("token", res.data.data);
      const [ee, r] = await to(API.socketIoPort());
      if (ee) {
        log(ee.message);
        setIsVisible(true);
        setCheckError("获取行情信息端口失败");
        setTimeout(() => {
          setIsVisible(false);
        }, 3000);
      } else {
        setStore("socketport", r.data.data);
        navigate("/home");
      }
    }

    setIsLoginIng(false);
  };
  return (
    <div className="flex-1 flex flex-col justify-center items-center px-8 py-12 ">
      <MyAlert checkError={checkError} isVisible={isVisible} />
      <div className="card card-side bg-base-100 shadow-xl">
        <figure className="w-full h-full">
          <img
            className="w-full h-full"
            src="https://daisyui.com/images/stock/photo-1635805737707-575885ab0820.jpg"
            alt="Movie"
          />
        </figure>
        <div className="card-body h-fit">
          <div className="w-30 h-full border-r-2 border-2 border-gray-200 rounded-lg p-16 bg-yellow-50">
            <h1 className="text-3xl font-semibold mb-6 text-blue-500 text-center bold border-lime-300">
              金洲量化
            </h1>

            <div className="mt-6">
              <label htmlFor="username" className="text-gray-500">
                用户名
                <div className="flex items-center">
                  <input
                    id="username"
                    type="text"
                    className=" font-semibold text-black input input-bordered input-secondary block w-full rounded-lg border border-gray-200 p-2 focus:outline-none focus:border-blue-500 bg-white"
                    placeholder=""
                    value={username}
                    onChange={(e: { target: { value: any } }) =>
                      setUsername(e.target.value)
                    }
                  />
                  <MyReset onReset={() => setUsername("")} />
                </div>
              </label>
            </div>
            <div className="mt-6">
              <label htmlFor="password" className="text-gray-500">
                密码
                <div className="flex items-center">
                  <input
                    id="password"
                    type="password"
                    className="font-semibold text-black input input-bordered input-primary block w-full rounded-lg border border-gray-200 p-2 focus:outline-none focus:border-blue-500 bg-white"
                    placeholder=""
                    value={password}
                    onChange={(e: { target: { value: any } }) =>
                      setPassword(e.target.value)
                    }
                  />
                  <MyReset onReset={() => setPassword("")} />
                </div>
              </label>
            </div>
            <div className="mt-6">
              <label htmlFor="serverIP" className="text-gray-500">
                服务IP
                <div className="flex items-center">
                  <input
                    id="serverIP"
                    type="text"
                    className="font-semibold text-black input input-bordered input-primary block w-full rounded-lg border border-gray-200 p-2 focus:outline-none focus:border-blue-500 bg-white"
                    placeholder=""
                    value={domain}
                    onFocus={(e: { target: { select: () => void } }) => {
                      setDomain("");
                      e.target.select();
                    }}
                    onChange={(e: { target: { value: string } }) =>
                      setDomain(e.target.value)
                    }
                  />
                  <MyReset onReset={() => setDomain("")} />
                </div>
              </label>
            </div>
            <button
              className="relative btn bg-blue-500 text-white rounded-lg py-2 text-lg font-semibold mt-8 w-80"
              onClick={handleLogin}
              disabled={isLoginIng}
            >
              {" "}
              {isLoginIng ? (
                <span className="loading loading-spinner loading-lg text-primary" />
              ) : (
                <>
                  <span>
                    登&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;录
                  </span>
                  <kbd className="kbd kbd-sm absolute text-right right-4">
                    Enter
                  </kbd>
                </>
              )}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

export default Login;
